package com.caipu.service;

import com.alibaba.fastjson.JSON;
import com.caipu.config.DashScopeConfig;
import com.caipu.dto.AiImageGenerateRequest;
import com.caipu.dto.AiImageGenerateResponse;
import com.caipu.dto.AiImageTaskResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * AI图片生成服务
 */
@Slf4j
@Service
public class AiImageService {
    
    private final WebClient webClient;
    private final DashScopeConfig dashScopeConfig;
    
    @Autowired
    public AiImageService(DashScopeConfig dashScopeConfig) {
        this.dashScopeConfig = dashScopeConfig;
        this.webClient = WebClient.builder()
                .baseUrl(dashScopeConfig.getBaseUrl())
                .defaultHeader("Authorization", dashScopeConfig.getKey())
                .defaultHeader("Content-Type", "application/json")
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024))
                .build();
    }
    
    /**
     * 创建AI图片生成任务
     */
    public Mono<AiImageGenerateResponse> generateImage(AiImageGenerateRequest request) {
        String prompt = buildPrompt(request.getDishName());
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", dashScopeConfig.getModel());
        
        Map<String, Object> input = new HashMap<>();
        input.put("prompt", buildPrompt(request.getDishName()));
        requestBody.put("input", input);
        
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("size", request.getSize());
        parameters.put("n", request.getN());
        requestBody.put("parameters", parameters);
        
        return webClient.post()
                .uri("/api/v1/services/aigc/text2image/image-synthesis")
                .header("X-DashScope-Async", "enable")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .map(this::parseGenerateResponse)
                .doOnError(error -> log.error("AI图片生成失败", error))
                .onErrorReturn(createErrorResponse("图片生成请求失败"));
    }
    
    /**
     * 查询AI图片生成任务状态
     */
    public Mono<AiImageTaskResponse> getTaskStatus(String taskId) {
        return webClient.get()
                .uri("/api/v1/tasks/" + taskId)
                .retrieve()
                .bodyToMono(AiImageTaskResponse.class)
                .doOnError(error -> log.error("查询AI图片任务状态失败, taskId: {}", taskId, error));
    }
    
    /**
     * 构建图片生成提示词
     */
    private String buildPrompt(String dishName) {
        return String.format("一道精美的%s菜品，摆盘精致，色彩丰富，食材新鲜，专业美食摄影，高清画质，餐厅级别呈现", dishName);
    }
    
    /**
     * 解析生成响应
     */
    private AiImageGenerateResponse parseGenerateResponse(String responseBody) {
        try {
            Map<String, Object> responseMap = JSON.parseObject(responseBody, Map.class);
            AiImageGenerateResponse response = new AiImageGenerateResponse();
            response.setRequestId((String) responseMap.get("request_id"));
            
            Map<String, Object> output = (Map<String, Object>) responseMap.get("output");
            if (output != null) {
                response.setTaskId((String) output.get("task_id"));
                response.setTaskStatus((String) output.get("task_status"));
            }
            
            return response;
        } catch (Exception e) {
            log.error("解析AI图片生成响应失败", e);
            return createErrorResponse("响应解析失败");
        }
    }
    
    /**
     * 创建错误响应
     */
    private AiImageGenerateResponse createErrorResponse(String errorMessage) {
        AiImageGenerateResponse response = new AiImageGenerateResponse();
        response.setErrorMessage(errorMessage);
        response.setTaskStatus("FAILED");
        return response;
    }
}